package com.ricky.room.normal

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.room.Room
import com.ricky.room.databinding.ActivityMainBinding
import com.ricky.room.db.User
import com.ricky.room.db.UserDataBase
import kotlinx.coroutines.*
import java.lang.Exception

class MainActivity : AppCompatActivity(), CoroutineScope by MainScope() {
    private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    private val dataBase: UserDataBase by lazy {
        Room.databaseBuilder(this, UserDataBase::class.java, "user.db").build()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btnInsert.setOnClickListener {
            launch {
                withContext(Dispatchers.IO) {
                    dataBase.userDao().insertUser(createUser())
                }
                updateView()
                Toast.makeText(this@MainActivity, "Insert success", Toast.LENGTH_SHORT).show()
            }
        }
        binding.btnDelete.setOnClickListener {
            launch {
                withContext(Dispatchers.IO) {
                    dataBase.userDao().deleteUser(createUser().copy(id=getUid()))
                }
                updateView()
                Toast.makeText(this@MainActivity, "Delete success", Toast.LENGTH_SHORT).show()
            }
        }
        binding.btnDelete.setOnLongClickListener {
            launch {
                withContext(Dispatchers.IO) {
                    dataBase.userDao().deleteAll()
                }
                updateView()
                Toast.makeText(this@MainActivity, "Delete all success", Toast.LENGTH_SHORT).show()
            }
            true
        }
        binding.btnUpdate.setOnClickListener {
            launch {
                withContext(Dispatchers.IO) {
                    dataBase.userDao().updateUser(createUser().copy(id=getUid()))
                }
                updateView()
                Toast.makeText(this@MainActivity, "Update success", Toast.LENGTH_SHORT).show()
            }
        }
        binding.btnQuery.setOnClickListener {
            launch {
                val user = withContext(Dispatchers.IO) {
                    dataBase.userDao().queryByName(binding.etName.text.toString())
                }
                user?.let {
                    binding.tvInfo.text = "${it.id}-${it.name} ${it.gender} ${it.age}"
                }
                Toast.makeText(this@MainActivity, "Query success", Toast.LENGTH_SHORT).show()
            }
        }
        updateView()
    }

    private fun getUid(): Long {
        return try {
            binding.etId.text.toString().toLong()
        } catch (e: Exception) {
            0L
        }
    }

    private fun createUser(): User {
        val name = binding.etName.text.toString()
        val gender = binding.etGender.text.toString()
        val age = binding.etAge.text.toString()
        return User(name = name, gender = gender, age = age)
    }

    private fun updateView() {
        launch {
            val text = withContext(Dispatchers.IO) {
                val users = dataBase.userDao().queryAllUser()
                users.joinToString("\n") { "${it.id}-${it.name} ${it.gender} ${it.age}" }
            }
            binding.tvInfo.text = text
        }
    }
}